import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import {
  Drawer,
  Button,
  Spin,
  message,
  Form,
  Row,
  Col,
  Select,
  DatePicker,
  Input,
  Divider,
  Space,
  Typography,
  Upload,
  Dropdown,
  Menu,
} from 'antd';
import { useTablePipeline } from 'ali-react-table';
import { DownloadOutlined, PlusOutlined, CloseOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
//@ts-ignore
import { TjTable } from '@/pages/ETrade/components';
import { iconLook } from '@/assets/icon/index.js';
import { AntdBaseTable } from '@/base/TBaseTable';
import { TRDefault } from '@/components/index.js';
import planIcon from '@/assets/img/plan_icon.png';
import pLoading from '#/components/PLoading/index.js';
import {
  postContractDetail,
  getTradeType,
  getContractDel,
  postAddCounterParty,
  getTemplate,
  getStationRelatedHisContract,
  getStationRelatedTradeNotice,
} from '../../service';
import type {
  ISearchFormData,
  IFileAnalysisResult,
  IContractSourceType,
  ITradeType,
  IOptionType,
} from '../../type';
import {
  IDrawerType,
  IPositionsCalculateType,
  ITemplateType,
  IModalType,
  ITradeDirectionType,
  IPointerType,
  IDataTabeType,
} from '../../type';
import { RadioGroup, SelectGroup, ConfirmModal, Pointer } from '../index';
import {
  tradeOptions,
  positionsCalculateOptions,
  downLoadTemplate,
  pointerOptions,
  SAME_DATE,
} from '../../dictionary';
import {
  readWorkbookFromLocalFile,
  readWorkbook,
  ToFixed,
  TIME_ENUM,
  handleDownload,
} from '../../tool';
import styles from './index.less';
import moment from 'moment';

interface IProps {
  /**
   * 合约id
   */
  contractId?: string;
  /**
   * 刷新
   */
  flashKey?: number;
  /**
   *
   */
  stationId?: string;
  /**
   * 合约来源
   */
  contractSource?: IContractSourceType;
  /**
   * 抽屉的宽度
   */
  width?: string;
  /**
   * 表单选项值
   */
  searchFormData?: ISearchFormData;
  /**
   * 是否显示抽屉
   */
  visible?: boolean;
  /**
   * 关闭函数
   */
  onClose?: () => void;
  /**
   * 提交
   */
  onSubmit?: (data: any) => any;
  /**
   * 抽屉展示的状态
   */
  drawerType?: IDrawerType;
  /**
   * 提交/取消按钮loading状态
   */
  isLoading?: boolean;
}

const Detail = (props: IProps) => {
  const [form] = Form.useForm();
  const _positionsCalculateOptions =
    positionsCalculateOptions.filter((item) => item.value !== IPositionsCalculateType.ALL_TYPE) ||
    [];
  const {
    visible = false,
    width = '60%',
    drawerType = IDrawerType.ADD,
    isLoading = false,
    contractId,
    stationId,
    searchFormData,
    contractSource,
    onSubmit,
    onClose,
  } = props;
  const { dealElementOptions = [], dealElementModalOptions = [] } = searchFormData || {};
  const [data, setData] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<boolean>(false);
  const [contractionOptions, setContractionOptions] = useState<any>();
  const [addTradeRivalName, setAddTradeRivalName] = useState<string>('');
  const [downLoadTemplateIdList, setDownLoadTemplateIdList] = useState<
    { templateType: ITemplateType; fileId: string }[]
  >([]); // 下载模版的id
  const [tradeRivalList, setTradeRivalList] = useState<IOptionType[]>([]); // 交易对手列表
  const [connectSequenceList, setConnectSeqenceList] = useState<IOptionType[]>([]); // 关联序列列表
  const [connectContractList, setConnectContractList] = useState<IOptionType[]>([]); // 关联合约主体列表
  const [fileData, setFileData] = useState<{ uid: string; name: string }[]>([]);
  const [list, setList] = useState<any>([]); // 表格数据组；
  const [totalAmount, setTotalAmount] = useState<number>(0); // 总电量
  const [totalCost, setTotalCost] = useState<number>(0); //总电费
  const [diffDay, setDiffDay] = useState<number>(1); // 执行时间相差天数;
  const [averagePrice, setAveragePrice] = useState<number>(0); //均价
  const [fileType, setFileType] = useState<ITemplateType>();
  const [pointNum, setPointNum] = useState<IPointerType>(IPointerType.NINETY_SIX_POINT); // 时点
  const [columns, setColumns] = useState<any[]>([]);

  const isAllowEdit = drawerType !== IDrawerType.DETAIL; // 详情状态不允许编辑并且显示详情状态

  // 获取交易序列
  const getStationRelatedTradeNoticeData = async (params: { stationId: string }) => {
    const res = await getStationRelatedTradeNotice(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _connectSequenceList = res?.data
        ? res?.data?.map((item: { tradeSequenceId?: string; tradeSequenceName?: string }) => {
            return {
              label: item?.tradeSequenceName,
              value: item?.tradeSequenceId,
            };
          })
        : [];
      setConnectSeqenceList(_connectSequenceList);
    } else {
      setConnectSeqenceList([]);
      message.info(res?.message || '请求失败');
    }
  };

  // 获取交易对手
  const getContractDelData = async (params: {
    provinceId?: string;
    counterpartyName?: string;
    stationId?: string;
  }) => {
    const res = await getContractDel(params);
    const _stationList = dealElementOptions
      ?.filter((item) => item.regionId === params?.provinceId && item.value !== params?.stationId)
      ?.map((item) => ({ label: item?.label, value: item?.value }));
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _tradeRivalList = res?.results
        ? res?.results?.map(
            (item: {
              counterpartyId?: string;
              counterpartyName?: string;
              counterpartyType?: string;
              id?: number;
            }) => {
              return {
                label: item?.counterpartyName,
                value: item?.counterpartyId,
                counterpartyType: item?.counterpartyType,
              };
            },
          )
        : [];
      setTradeRivalList([..._stationList, ..._tradeRivalList]);
    } else {
      setTradeRivalList([..._stationList]);
      message.info(res?.message || '请求失败');
    }
  };

  // 获取关联主合约
  const getStationRelatedHisContractData = async (params: { stationId: string }) => {
    const res = await getStationRelatedHisContract(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _connectContractList = res?.data
        ? res?.data
            ?.map((item: { contractId?: string; contractName?: string }) => {
              return {
                label: item?.contractName,
                value: item?.contractId,
              };
            })
            ?.filter((item: IOptionType) => {
              return item?.value !== contractId;
            })
        : [];
      setConnectContractList(_connectContractList);
    } else {
      setConnectContractList([]);
      message.info(res?.message || '请求失败');
    }
  };

  const getColumns = (arrayTd?: string[]) => {
    const _columns = [
      {
        code: 'date',
        name: '',
        width: 100,
        lock: true,
        getCellProps(value: any, record: any, rowIndex: any) {
          if (rowIndex % 2 === 0) {
            return {
              rowSpan: 2,
            };
          }
        },
        render(v: string) {
          return v ? (v !== SAME_DATE ? moment(v).format('YYYYMMDD') : v) : '-';
        },
      },
      {
        code: 'type',
        name: '',
        width: 60,
        lock: true,
        render(v: string) {
          return v || '-';
        },
      },
    ];
    arrayTd?.forEach((item) => {
      _columns.push({
        code: item,
        name: item,
        width: 80,
        // @ts-ignore
        render(v: any, record: any) {
          const a: any = record.type === IDataTabeType.QUANTITY ? ToFixed(v, 3) : ToFixed(v, 2);
          return a ?? '-';
        },
      });
    });
    return _columns;
  };

  // 处理电量电价初始数据
  const dealOriginFileData = (data1: any, pointNum1: IPointerType, fileType1?: ITemplateType) => {
    let _data: any[] = [];
    const _keys = TIME_ENUM(pointNum1);
    setColumns(getColumns(_keys || TIME_ENUM(96)) || []);
    const _dateList = Object.keys(data1) || [];
    _dateList.forEach((item: string, index: number) => {
      let _obj = {};
      let _obj1 = {};
      data1[item]?.forEach((i: any, j: number) => {
        const key = _keys[j];
        _obj = {
          ..._obj,
          date:
            fileType1 === ITemplateType.DAYTIME_SAME_CURVE_NINETY_SIX_POINT ||
            fileType1 === ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT
              ? SAME_DATE
              : moment(item).format('YYYYMMDD'),
          type: IDataTabeType.QUANTITY,
          [key]: i.quantity,
          id: `${new Date().getTime()}${Math.ceil(Math.random() * 1000)}`,
        };
        _obj1 = {
          ..._obj1,
          date:
            fileType1 === ITemplateType.DAYTIME_SAME_CURVE_NINETY_SIX_POINT ||
            fileType1 === ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT
              ? SAME_DATE
              : moment(item).format('YYYYMMDD'),
          type: IDataTabeType.PRICE,
          [key]: i.price,
          id: `${new Date().getTime()}${Math.ceil(Math.random() * 1000)}-${index}`,
        };
      });
      _data.push(_obj);
      _data.push(_obj1);
    });
    _data =
      fileType1 === ITemplateType.DAYTIME_SAME_CURVE_NINETY_SIX_POINT ||
      fileType1 === ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT
        ? _data.slice(0, 2)
        : _data;
    return _data;
  };

  // 初始化数据
  const fetchData = async (params: {
    contractId?: string;
    contractSource?: IContractSourceType;
    stationId?: string;
  }) => {
    setLoading(true);
    setError(false);
    // 调取查询合约详情数据接口
    const res = await postContractDetail(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      getContractDelData({ provinceId: res?.data?.provinceId, stationId: res?.data?.stationId }); // 获取交易对手列表
      getStationRelatedTradeNoticeData({
        stationId: res?.data?.stationId,
      }); //获取关联序列列表
      getStationRelatedHisContractData({
        stationId: res?.data?.stationId,
      }); //获取关联合约
      const _contractDate =
        res?.data?.contractEndDate && res?.data?.contractStartDate
          ? [moment(res?.data?.contractStartDate), moment(res?.data?.contractEndDate)]
          : [];
      const _contractType =
        res?.data?.contractType && res?.data?.tradeMode
          ? [Number(res?.data?.contractType), Number(res?.data?.tradeMode)]
          : [];
      const _signingTime = res?.data?.signingTime ? moment(res?.data?.signingTime) : undefined;
      const _pointNum =
        drawerType === IDrawerType.DETAIL
          ? IPointerType.NINETY_SIX_POINT
          : res?.data?.priceFluctuationDataType ===
              ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT ||
            res?.data?.priceFluctuationDataType === ITemplateType.DIURNAL_TWENTY_FOUR_POINT
          ? IPointerType.TWENTY_FOUR_POINT
          : IPointerType.NINETY_SIX_POINT;
      const _data =
        drawerType === IDrawerType.DETAIL
          ? res?.data?.priceFluctuationOf96 || []
          : res?.data?.priceFluctuationDataType ===
              ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT ||
            res?.data?.priceFluctuationDataType === ITemplateType.DIURNAL_TWENTY_FOUR_POINT
          ? res?.data?.priceFluctuationOf24 || []
          : res?.data?.priceFluctuationOf96 || [];
      const _fileType =
        res?.data?.priceFluctuationDataType || ITemplateType.DIURNAL_NINETY_SIX_POINT;
      const _list = dealOriginFileData(_data, _pointNum, _fileType);
      const _totalAmount = res?.data?.totalContractQuantity ?? 0;
      const _totalCost = res?.data?.totalContractIncome ?? 0;
      const _diffDay =
        _contractDate.length > 0 ? moment(_contractDate[1]).diff(_contractDate[0], 'day') : 1;
      setPointNum(_pointNum);
      setList(_list);
      setData(res?.data || {});
      setFileData([]);
      setTotalAmount(_totalAmount);
      setAveragePrice(res?.data?.totalContractPrice ?? 0);
      setTotalCost(_totalCost);
      setDiffDay(_diffDay);
      setFileType(_fileType);
      form &&
        form.setFieldsValue({
          ...res?.data,
          contractDate: _contractDate,
          contractType: _contractType,
          signingTime: _signingTime,
        });
      setError(false);
    } else {
      setError(true);
      message.info(res?.message || '请求失败');
    }
    setLoading(false);
  };

  // 处理合约类型数据
  const dealContractType = (list1: ITradeType[]) => {
    const _list: IOptionType[] = list1?.map((item) => {
      const _children = item?.tradeTypeChildren
        ? item?.tradeTypeChildren.map((i) => {
            return { label: i.codeName, value: i.codeId } as IOptionType;
          })
        : null;
      return {
        label: item.codeName,
        value: item.codeId,
        children: _children,
      } as IOptionType;
    });
    return _list || [];
  };

  // 设定仓位计算/合约类型
  const getContractType = (options: IOptionType[]) => {
    const _contractionObj = options?.find((item: any) => item.label === '中长期');
    const _contractionChildrenObj = _contractionObj?.children?.find(
      (item: any) => item.label === '直接交易',
    );
    const _contractType = [_contractionObj?.value, _contractionChildrenObj?.value];
    form &&
      form.setFieldsValue({
        contractType: _contractType,
        storageCapacityCalc: IPositionsCalculateType.TAKE_PART_IN,
      });
  };

  // 获取合约类型
  const getContractionType = async () => {
    const res = await getTradeType();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _contractionOptions = dealContractType(res.data);
      setContractionOptions(_contractionOptions);
      getContractType(_contractionOptions);
    } else {
      message.info(res?.message || '请求失败');
    }
  };

  // 取消
  const _onCancel = () => {
    onClose && onClose();
  };

  // 删除已上传的文件
  const handleDeleteFile = () => {
    setList([]);
    setFileData([]);
    setTotalAmount(0);
    setAveragePrice(0);
    setColumns([]);
  };

  // 重置
  const onReset = () => {
    form && form.resetFields();
    form && form.setFieldsValue({});
    setAveragePrice(0);
    setTotalCost(0);
    setTotalAmount(0);
    setDiffDay(1);
    handleDeleteFile();
    setConnectContractList([]);
    setConnectSeqenceList([]);
    setTradeRivalList([]);
    setFileData([]);
    setList([]);
    setFileType(undefined);
    getContractType(contractionOptions);
  };

  // 处理上传数据
  const dealFildData = (data1: any[]) => {
    const _data: any = {};
    const _keys = TIME_ENUM(pointNum);
    data1?.forEach((item: any, index) => {
      if (index % 2 === 0) {
        const { date } = item;
        let arr = [];
        let timeOrder = 0;
        const _date =
          fileType === ITemplateType.DAYTIME_SAME_CURVE_NINETY_SIX_POINT ||
          fileType === ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT
            ? moment(new Date()).format('YYYY-MM-DD')
            : moment(date).format('YYYY-MM-DD');
        const _priceObj = data1[index + 1] || {};
        arr = _keys.map((i) => {
          timeOrder += 1;
          return {
            quantity: item[i] ?? 0,
            price: _priceObj[i] ?? 0,
            timeOrder,
          };
        });
        _data[_date] = arr;
      }
    });
    return _data;
  };

  // 提交按钮
  const _onSubmit = () => {
    form &&
      form.validateFields().then(async (values) => {
        if (list && list.length > 0) {
          const {
            contractDate,
            signingTime,
            parentContractId,
            tradeSequenceId,
            contractType = [],
            counterStationId,
            ...rest
          } = values || {};
          const _contractStartDate = contractDate
            ? moment(contractDate[0]).format('YYYY-MM-DD')
            : '';
          const _contractEndDate = contractDate ? moment(contractDate[1]).format('YYYY-MM-DD') : '';
          const _signingTime = signingTime ? moment(signingTime).format('YYYY-MM-DD') : '';
          const _obj = dealElementOptions?.find((item) => item.value === values.stationId);
          const _provinceId = _obj?.regionId;
          const _provinceName = dealElementModalOptions?.find(
            (item) => item.regionId === _provinceId,
          )?.label;
          const _priceFluctuation = dealFildData(list);
          const _parentContractName =
            connectContractList?.find((item) => item.value === parentContractId)?.label || '';
          const _tradeSequenceName =
            connectSequenceList?.find((item) => item.value === tradeSequenceId)?.label || '';
          const _counterStationName =
            tradeRivalList?.find((item) => item.value === counterStationId)?.label || '';
          const _stationName = _obj?.label || '';
          const _data = {
            ...rest,
            stationId: values?.stationId || stationId,
            contractStartDate: _contractStartDate,
            contractEndDate: _contractEndDate,
            signingTime: _signingTime,
            provinceId: _provinceId,
            provinceName: _provinceName,
            priceFluctuationDataType: fileType,
            contractType: contractType[0],
            tradeMode: contractType[1],
            priceFluctuation: _priceFluctuation,
            parentContractId,
            parentContractName: _parentContractName,
            tradeSequenceId,
            tradeSequenceName: _tradeSequenceName,
            counterStationId: counterStationId,
            stationName: _stationName,
            counterStationName: _counterStationName,
            contractId,
          };
          const res = onSubmit && (await onSubmit(_data));
          if (res && res.statusCode === HttpCode.SUCCESS) {
            _onCancel();
          }
        } else {
          message.info('请导入数据文件');
        }
      });
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { value, label } = option;
    return (
      value?.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  // 选择合约主体
  const onChangeStation = (e: any) => {
    const _obj = dealElementOptions?.find((item) => item.value === e);
    getContractDelData({ provinceId: _obj?.regionId, stationId: e });
    getStationRelatedTradeNoticeData({ stationId: e });
    getStationRelatedHisContractData({ stationId: e });
    form &&
      form.setFieldsValue({
        counterStationId: '',
        tradeSequenceId: '',
        parentContractId: '',
      });
  };

  // 获取总电量，总电费，均价
  const getCost = (
    totalAmount1: number,
    totalCost1: number,
    diffDay1: number,
    oldDiffDay: number,
    fileType1?: ITemplateType,
  ) => {
    let _totalAmount = totalAmount1;
    let _totalCost = totalCost1;
    let _averagePrice = totalAmount1 === 0 ? 0 : totalCost1 / totalAmount1;
    if (
      fileType1 === ITemplateType.DAYTIME_SAME_CURVE_NINETY_SIX_POINT ||
      fileType1 === ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT
    ) {
      _totalAmount = (_totalAmount / oldDiffDay) * diffDay1;
      _totalCost = (_totalCost / oldDiffDay) * diffDay1;
      _averagePrice = totalAmount1 === 0 ? 0 : _totalCost / _totalAmount;
    }
    setDiffDay(diffDay1);
    return {
      diffDay,
      totalAmount: _totalAmount,
      totalCost: _totalCost,
      averagePrice: _averagePrice,
    };
  };

  // 改变执行时间
  const onChangeContractDate = (e: any) => {
    const _diffDay = e.length > 0 ? moment(e[1]).diff(e[0], 'day') + 1 : 1;
    const cost = getCost(totalAmount, totalCost, _diffDay, diffDay, fileType);
    setTotalAmount(cost?.totalAmount ?? 0);
    setTotalCost(cost?.totalCost ?? 0);
    setAveragePrice(cost?.averagePrice ?? 0);
  };

  // 交易对手/关联合约/关联序列 应先选交易主体
  const onFocus = () => {
    if (form && !form.getFieldValue('stationId')) {
      message.error('请先选择合约主体');
    }
  };

  // 自定义交易对手
  const onChangeAddTradeRivalName = (e: any) => {
    setAddTradeRivalName(e.target.value);
  };

  // 新增交易对手
  const handleAddTradeRival = async () => {
    const _stationId = form && form.getFieldValue('stationId');
    const _obj = _stationId
      ? dealElementOptions?.find((item) => item.value === _stationId)
      : undefined;
    const res = await postAddCounterParty({
      counterPartyName: addTradeRivalName,
      provinceId: _obj?.regionId,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      getContractDelData({
        provinceId: _obj?.regionId,
        stationId: _stationId,
      });
      setAddTradeRivalName('');
      message.info('新增成功');
    } else {
      message.info(res?.message || '新增失败');
    }
  };

  // 解析文件
  const analysisFile = (workbook: any) => {
    const results = {
      isUseTemplate: false, //文件是否未是使用模版文件
      isLargeFile: false, // 是否大于5000行
      isEmpty: false, // 文件是否为空
      isNumber: false, //文件是否不为数字
      isQualified: true, //文件是否合格
      fileType: ITemplateType.DAYTIME_SAME_CURVE_NINETY_SIX_POINT, // 文件类型
      data: [], // 文件数据
      totalAmount: 0, // 总电量
      averagePrice: 0, // 平均电价
      arrayTd: [], // 表头
    };
    if (!workbook) {
      // 判断数据是否为空
      return {
        ...results,
        isQualified: false,
        isUseTemplate: true,
      };
    } else {
      const excelJson = readWorkbook(workbook); //// 判断数据是否为空
      if (!excelJson || excelJson.length === 0) {
        return {
          ...results,
          isQualified: false,
          isEmpty: true,
        };
      } else {
        const SheetNames = workbook.SheetNames;
        const Sheets = workbook.Sheets;
        const nowSheet = Sheets[SheetNames[0]];
        const _sheetsArry = Object.values(nowSheet);
        const arrayColB: any = _sheetsArry.filter((item1: any) => {
          return item1?.w === IDataTabeType.QUANTITY || item1?.w === IDataTabeType.PRICE;
        });
        const _list: any[] = [];
        excelJson?.forEach((item2: any, index: number) => {
          const _dateKey = '请注意保持表头格式';
          const { __EMPTY_1, __EMPTY, __rowNum__, 请注意保持表头格式, ...rest } = item2;
          const _dateValue = item2[_dateKey] || item2.__EMPTY;
          const _dateObj: any = _sheetsArry?.find((item3: any) => item3?.v === _dateValue);
          const _date = (_dateObj && _dateObj?.w) || _dateValue;
          if (Object.values(rest).length > 0) {
            _list.push({
              ...rest,
              type: item2.__EMPTY_1 || item2.__EMPTY || arrayColB[index]?.v || '',
              date: index % 2 === 0 ? _date : _list[index - 1].date,
              id: `${index}`,
            });
          }
        });
        if (_list.length <= 0) {
          return {
            ...results,
            isQualified: false,
            isEmpty: true,
          };
        } else if (_list.length > 5000) {
          // 判断数据是否大于5000行
          return {
            ...results,
            isQualified: false,
            isLargeFile: true,
          };
        } else {
          let isUseTemplate = false;
          let isEmpty = false;
          let isNumber = false;
          const columns96 = TIME_ENUM(96);
          const columns24 = TIME_ENUM(24);
          let allItemKeyArr: any[] = [];
          _list.forEach((item, index) => {
            const { type, date, id, ...rest } = item;
            const itemValueArr = Object.values(rest).map((item1) => Number(_.trim(item1)));
            const itemKeyArr = Array.from(new Set(Object.keys(rest))).map((item2: any) =>
              _.trim(item2),
            );
            allItemKeyArr = [...allItemKeyArr, ...itemKeyArr];
            if (
              (date !== SAME_DATE && !!Number.isNaN(new Date(date).valueOf())) ||
              !(
                (type === IDataTabeType.QUANTITY && index % 2 === 0) ||
                (type === IDataTabeType.PRICE && index % 2 === 1)
              )
            ) {
              isUseTemplate = true;
            }
            if (
              itemValueArr?.length !== IPointerType.TWENTY_FOUR_POINT &&
              itemValueArr?.length !== IPointerType.NINETY_SIX_POINT
            ) {
              isEmpty = true;
            }
            itemValueArr.forEach((item3) => {
              if (!_.isNumber(item3) || isNaN(item3)) {
                isNumber = true;
              }
            });
          });
          allItemKeyArr = Array.from(new Set(allItemKeyArr));
          const _column =
            allItemKeyArr.length === IPointerType.TWENTY_FOUR_POINT ? columns24 : columns96;
          _column.forEach((j) => {
            if (!allItemKeyArr?.find((i) => i === j)) {
              isUseTemplate = true;
            }
          });
          if (isEmpty || isNumber || isUseTemplate) {
            return {
              ...results,
              isQualified: false,
              isUseTemplate,
              isNumber,
              isEmpty,
            };
          } else if (
            (_list[0].date === SAME_DATE && _list.length !== 2) ||
            _list.length % 2 !== 0
          ) {
            return {
              ...results,
              isQualified: false,
              isUseTemplate: true,
            };
          } else {
            let _totalAmount = 0;
            let _totalCost = 0;
            const electricityArray = _list.filter((item, index) => {
              return index % 2 === 0;
            });
            const electricityPricesArray = _list.filter((item, index) => {
              return index % 2 === 1;
            });
            const { type, date, id, ...rest } = _list[0];
            const itemValueArr = Object.values(rest);
            const _fileType =
              date === SAME_DATE
                ? itemValueArr.length === IPointerType.TWENTY_FOUR_POINT
                  ? ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT
                  : ITemplateType.DAYTIME_SAME_CURVE_NINETY_SIX_POINT
                : itemValueArr.length === IPointerType.TWENTY_FOUR_POINT
                ? ITemplateType.DIURNAL_TWENTY_FOUR_POINT
                : ITemplateType.DIURNAL_NINETY_SIX_POINT;
            const _arrayTd =
              _fileType === ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT ||
              _fileType === ITemplateType?.DIURNAL_TWENTY_FOUR_POINT
                ? columns24
                : columns96;
            electricityArray.forEach((item, index) => {
              _arrayTd.forEach((i) => {
                _totalAmount += Number(item[i]);
                _totalCost += Number(item[i]) * Number(electricityPricesArray[index][i]);
              });
            });
            return {
              ...results,
              isQualified: true,
              fileType: _fileType,
              arrayTd: _arrayTd,
              totalAmount: _totalAmount,
              totalCost: _totalCost,
              // averagePrice: _totalCost / _totalAmount,
              data: _list,
            };
          }
        }
      }
    }
  };

  // 导入文件
  const customRequest = async ({ file }: any) => {
    if (file.status !== 'uploading' && file.status !== 'removed') {
      pLoading.show('上传附件中...');
      const pdata = new window.FormData();
      pdata.append('file', file);
      pdata.append('fileName', file.name);
      pLoading.dismiss();
      readWorkbookFromLocalFile(file, async (workbook: any) => {
        try {
          // @ts-ignore
          const res: IFileAnalysisResult = analysisFile(workbook);
          if (res.isQualified) {
            const fileList = [file];
            const _contractDate = form && form.getFieldValue('contractDate');
            const _diffDay =
              _contractDate && _contractDate.length > 0
                ? moment(_contractDate[1]).diff(_contractDate[0], 'day') + 1
                : 1;
            const _totalAmount = res?.totalAmount ?? 0;
            const _totalCost = res?.totalCost ?? 0;
            const _fileType = res?.fileType;
            const _pointNum =
              _fileType === ITemplateType.DAYTIME_SAME_CURVE_TWENTY_FOUR_POINT ||
              _fileType === ITemplateType.DIURNAL_TWENTY_FOUR_POINT
                ? IPointerType.TWENTY_FOUR_POINT
                : IPointerType.NINETY_SIX_POINT;
            const cost = getCost(_totalAmount, _totalCost, _diffDay, 1, _fileType);
            form &&
              form.setFieldsValue({
                tradeRole: _totalAmount > 0 ? ITradeDirectionType.SELL : ITradeDirectionType.BUY,
              });
            setFileData(fileList);
            setPointNum(_pointNum);
            setTotalAmount(cost?.totalAmount ?? 0);
            setTotalCost(cost?.totalCost ?? 0);
            setAveragePrice(cost?.averagePrice ?? 0);
            setList(res?.data || []);
            setFileType(_fileType);
            setColumns(getColumns(res?.arrayTd || TIME_ENUM(96)) || []);
          } else {
            let hintText = '';
            if (res.isUseTemplate) {
              hintText = '文件解析失败，请重新上传';
            } else if (res.isLargeFile) {
              hintText = '文件过大，请联系管理员进行后端上传';
            } else if (res.isEmpty) {
              hintText = '合约数据存在空项，请重新上传';
            } else if (res.isNumber) {
              hintText = '合约数据存在非数字，请重新上传';
            }
            await ConfirmModal.show({
              title: '提醒',
              hintText,
              type: IModalType.CONFIRM,
              onOk: () => {},
            });
          }
        } catch {
          const hintText = '文件解析函数错误，请联系相关人员';
          await ConfirmModal.show({
            title: '提醒',
            hintText,
            type: IModalType.CONFIRM,
            onOk: () => {},
          });
        }
      });
    }
  };

  // // 判断是不是数字
  // const toDetermineData = (v: string) => {
  //   const reg = /^[\d|\.]*$/;
  //   return reg.test(v);
  // };

  // 获取模版id
  const getTemplateList = async () => {
    const res = await getTemplate();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setDownLoadTemplateIdList(res?.data || []);
    } else {
      setDownLoadTemplateIdList([]);
      message.info(res?.message || '请求失败');
    }
  };

  // 下载模版
  const onDownLoad = (e: any) => {
    const _annexId = downLoadTemplateIdList?.find((item) => item.templateType === e.key)?.fileId;
    handleDownload({ annexId: _annexId }, false);
  };

  // 24点和96点切换
  const onChangePointNum = (e: IPointerType) => {
    let res = [];
    if (e === IPointerType.NINETY_SIX_POINT) {
      res = dealOriginFileData(data?.priceFluctuationOf96, IPointerType.NINETY_SIX_POINT, fileType);
    } else {
      res = dealOriginFileData(
        data?.priceFluctuationOf24,
        IPointerType.TWENTY_FOUR_POINT,
        fileType,
      );
    }
    setList(res);
    setPointNum(e);
  };

  useEffect(() => {
    getContractionType();
    if (drawerType !== IDrawerType.DETAIL) {
      getTemplateList();
    }
  }, []);

  useEffect(() => {
    if (drawerType !== IDrawerType.ADD && contractId && visible) {
      const params = {
        contractId,
        contractSource,
        stationId,
      };
      fetchData(params);
    } else {
      onReset();
    }
  }, [contractId, contractSource, stationId, visible]);

  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: list, columns: columns as any })
    .primaryKey('id')
    .appendRowPropsGetter((): any => {
      const color = '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
      取消
    </Button>,
    <Button
      key="dtest2"
      type="primary"
      onClick={_onSubmit}
      loading={isLoading}
      style={{ marginLeft: 16 }}
    >
      确定
    </Button>,
  ];

  const menu = (
    <Menu onClick={onDownLoad}>
      {downLoadTemplate.map((item) => {
        return <Menu.Item key={item.value}>{item.label}</Menu.Item>;
      })}
    </Menu>
  );

  return (
    <Drawer
      width={width}
      className={styles.operateLogModal}
      visible={visible}
      destroyOnClose={true}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>
            {drawerType === IDrawerType.ADD
              ? '新建合约'
              : drawerType === IDrawerType.EDIT
              ? '编辑合约'
              : '合约详情'}
          </span>
        </div>
      }
      footer={drawerType === IDrawerType.DETAIL ? null : footerRender()}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin spinning={loading} />
        ) : error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : data ? (
          <div className={styles.content}>
            <Form
              className={isAllowEdit ? styles.form : styles.disabledForm}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
              form={form}
              colon={false}
              labelAlign="left"
              autoComplete="off"
              requiredMark={false}
            >
              <Row>
                <Col span={12}>
                  <Form.Item
                    name={isAllowEdit ? 'stationId' : undefined}
                    label="合约主体"
                    rules={[{ required: true, message: '请选择合约主体' }]}
                  >
                    {isAllowEdit ? (
                      <Select
                        placeholder={'合约主体'}
                        showArrow={true}
                        disabled={drawerType === IDrawerType.EDIT}
                        options={
                          dealElementOptions?.map((item) => ({
                            label: item?.label,
                            value: item?.value,
                          })) as any[]
                        }
                        showSearch={true}
                        filterOption={filterOption as any}
                        onChange={onChangeStation}
                      />
                    ) : (
                      data?.stationName || '-'
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    name={isAllowEdit ? 'tradeRole' : undefined}
                    label="交易方向"
                    initialValue={ITradeDirectionType.SELL}
                    rules={[{ required: true, message: '请选择交易方向' }]}
                  >
                    {isAllowEdit ? (
                      <RadioGroup options={tradeOptions} disabled={true} />
                    ) : (
                      tradeOptions?.find((item) => item.value === data?.tradeRole)?.label || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item
                    name={isAllowEdit ? 'contractDate' : undefined}
                    label="执行时段"
                    rules={[{ required: true, message: '请选择执行时段' }]}
                  >
                    {isAllowEdit ? (
                      <DatePicker.RangePicker
                        style={{ width: '100%' }}
                        format="YYYYMMDD"
                        placeholder={['开始时间', '结束时间']}
                        onChange={onChangeContractDate}
                      />
                    ) : data?.contractStartDate && data?.contractEndDate ? (
                      `${moment(data?.contractStartDate).format('YYYYMMDD')}-${moment(
                        data?.contractEndDate,
                      ).format('YYYYMMDD')}`
                    ) : (
                      '-'
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    name={isAllowEdit ? 'storageCapacityCalc' : undefined}
                    label="仓位计算"
                    rules={[{ required: true, message: '请选择仓位计算' }]}
                  >
                    {isAllowEdit ? (
                      <Select
                        placeholder={'仓位计算'}
                        showArrow={true}
                        options={_positionsCalculateOptions as any[]}
                      />
                    ) : (
                      _positionsCalculateOptions?.find(
                        (item) => item.value === data?.storageCapacityCalc,
                      )?.label || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name={isAllowEdit ? 'contractName' : undefined}
                    label="合约名称"
                    rules={[
                      { required: true, message: '请填写合约名称' },
                      { max: 100, message: '合约名称不可超过100个字符' },
                    ]}
                    labelCol={{ span: 2 }}
                    wrapperCol={{ span: 24 }}
                  >
                    {isAllowEdit ? (
                      <Input.TextArea maxLength={100} placeholder="请填写合约名称" />
                    ) : (
                      data?.contractName || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item
                    name={isAllowEdit ? 'contractType' : undefined}
                    label="合约类型"
                    rules={[{ required: true, message: '请选择合约类型' }]}
                  >
                    {isAllowEdit ? (
                      <SelectGroup options={contractionOptions as any} />
                    ) : (
                      `${
                        contractionOptions?.find(
                          (item: any) => item.value === Number(data?.contractType),
                        )?.label || '-'
                      }/${
                        contractionOptions
                          ?.find((item: any) => item.value === Number(data?.contractType))
                          ?.children?.find((item: any) => item.value === Number(data?.tradeMode))
                          ?.label || '-'
                      }`
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item name={isAllowEdit ? 'counterStationId' : undefined} label="交易对手">
                    {isAllowEdit ? (
                      <Select
                        placeholder={'交易对手'}
                        showArrow={true}
                        options={tradeRivalList as any[]}
                        showSearch={true}
                        onFocus={onFocus}
                        filterOption={filterOption as any}
                        dropdownClassName={styles.dropdown}
                        dropdownRender={(menu1) => (
                          <div className={styles.dropdownRender}>
                            {menu1}
                            <Divider />
                            <Space align="center">
                              <Input
                                placeholder="请输入"
                                value={addTradeRivalName}
                                onChange={onChangeAddTradeRivalName}
                                max={20}
                              />
                              <Typography.Link
                                onClick={handleAddTradeRival}
                                style={{ whiteSpace: 'nowrap' }}
                              >
                                <PlusOutlined /> 新增
                              </Typography.Link>
                            </Space>
                          </div>
                        )}
                      />
                    ) : (
                      data?.counterStationName || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item name={isAllowEdit ? 'signingTime' : undefined} label="签约时间">
                    {isAllowEdit ? (
                      <DatePicker
                        format="YYYYMMDD"
                        placeholder="请选择签约时间"
                        style={{ width: '100%' }}
                      />
                    ) : data?.signingTime ? (
                      moment(data.signingTime).format('YYYYMMDD')
                    ) : (
                      '-'
                    )}
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item name={isAllowEdit ? 'tradeSequenceId' : undefined} label="关联序列">
                    {isAllowEdit ? (
                      <Select
                        placeholder={'关联序列'}
                        showArrow={true}
                        onFocus={onFocus}
                        options={connectSequenceList as any[]}
                        showSearch={true}
                        filterOption={filterOption as any}
                      />
                    ) : (
                      data?.tradeSequenceName || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name={isAllowEdit ? 'parentContractId' : undefined}
                    label="关联主合约"
                    labelCol={{ span: 2 }}
                    wrapperCol={{ span: 24 }}
                  >
                    {isAllowEdit ? (
                      <Select
                        placeholder={'关联主合约'}
                        showArrow={true}
                        options={connectContractList as any[]}
                        showSearch={true}
                        onFocus={onFocus}
                        filterOption={filterOption as any}
                      />
                    ) : (
                      data?.parentContractName || '-'
                    )}
                  </Form.Item>
                </Col>
              </Row>
            </Form>
            {isAllowEdit ? (
              <Row className={styles.import}>
                <Col span={2} className={styles.label}>
                  导入文件
                </Col>
                <Dropdown
                  overlay={menu}
                  placement="bottomCenter"
                  overlayClassName={styles.dropdownA}
                >
                  <Col span={2} className={styles.downLoad}>
                    下载模板
                  </Col>
                </Dropdown>
              </Row>
            ) : null}
            <Row className={drawerType === IDrawerType.DETAIL ? styles.detail : styles.file}>
              {drawerType === IDrawerType.DETAIL ? (
                <Pointer value={pointNum} options={pointerOptions} onChange={onChangePointNum} />
              ) : list.length > 0 && fileData.length > 0 ? (
                <div className={styles.left}>
                  <img src={iconLook} className={styles.fileLogo} />
                  <span className={styles.fileName}>{fileData[0]?.name}</span>
                  <span className={styles.fileDelete} onClick={handleDeleteFile}>
                    <CloseOutlined />
                  </span>
                </div>
              ) : (
                <div className={styles.upload}>
                  <Upload
                    customRequest={customRequest}
                    fileList={fileData as any}
                    maxCount={1}
                    accept=".xlsx, .xls"
                  >
                    <DownloadOutlined className={styles.logo} />
                    <a className={styles.text}>导入</a>
                  </Upload>
                </div>
              )}
              {list.length > 0 ? (
                <div className={styles.right}>
                  <div className={styles.totalAmount}>
                    <span className={styles.label}>合约总电量：</span>
                    <span className={styles.value}>{ToFixed(totalAmount) ?? '-'}MWh</span>
                  </div>
                  <div className={styles.averagePrice}>
                    <span className={styles.label}>合约均价：</span>
                    <span className={styles.value}>{ToFixed(averagePrice, 2) ?? '-'}元/MWh</span>
                  </div>
                </div>
              ) : null}
            </Row>
            <div className={styles.antdBaseTable}>
              {list?.length > 0 ? (
                <div className={styles.tableContent}>
                  <TjTable
                    useVirtual="auto"
                    style={{
                      '--row-height': '28px',
                      // '--header-bgcolor': '#383C3E',
                      '--header-row-height': '28px',
                      '--cell-padding': '4px 16px',
                      '--cell-border-vertical': '1px solid #4E5154',
                      '--header-cell-border-vertical': '1px solid #4E5154',
                      '--highlight-bgcolor': '#21323E',
                    }}
                    {...pipeline.getProps()}
                  />
                </div>
              ) : drawerType !== IDrawerType.DETAIL ? null : (
                <TRDefault type={'emptysm'} message={'暂无数据'} />
              )}
            </div>
          </div>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </Drawer>
  );
};

export default Detail;
